using System.Text;
using TrackSystem.IO.Data;
using TrackSystem.IO.Models;

namespace TrackSystem.IO.Protocol
{
    /// <summary>
    /// 国产高度计通信协议
    /// </summary>
    public class HDCS200Protocol : ProtocolBase
    {
        private int startTicks;
        private bool bSendR;
        private bool autoMode;
        private bool autoGet;
        private String rx_auto = "$1,21,1, LAKEAS*02FA";
        private String rx_query = "$1,21,1,ASYTRS*032F";
        private byte[] Tx_r2; // 

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public HDCS200Protocol(string name)
            : base()
        {
            NeedInit = false;
            Name = name;
            Tx_r = Encoding.UTF8.GetBytes(rx_auto); // 自动模式
            Tx_r2 = Encoding.UTF8.GetBytes(rx_query); // 询问模式
            bSendR = false;
            autoMode = false;
            autoGet = false;
        }

        /// <summary>
        /// 生成读取寄存器的通讯帧
        /// </summary>
        /// <returns></returns>
        public override byte[] GenerateReadFrame(out int NeedRecvLen)
        {
            startTicks = Environment.TickCount;
            // 上次的发送没有收到正确回复，bSend没有被置位
            if (bSendR)
            {
                Fail_R++;
                // 失败超过3次，成功次数清零
                if (Fail_R >= 3)
                {
                    Succ_R = 0;
                }
            }
            bSendR = true;

            NeedRecvLen = 4;
            if (autoMode)
            {
                if (autoGet)
                    return null; // 已正常应答
                else
                    return Tx_r; // 发送自动触发命令
            }
            else {
                return Tx_r2;
            }

        }


        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override bool ProcessReadFrame(byte[] buffer)
        {
            Rx_r = buffer;
            Lapse = Environment.TickCount - startTicks;
            try
            {
                string frame = Encoding.UTF8.GetString(buffer);
                string[] ar_line = frame.Split(',');
                if (ar_line[3] == "result") {
                    Succ_R++;
                    bSendR = false;     // 正确收到，标志位变为false
                    Fail_R = 0;         // 通信成功，则将失败次数清零   
                    if (ar_line[4] == "FF")
                    {
                        RegFactory.Instance.SetVal(RegNameList[0], -1.0);
                    }
                    else {
                        RegFactory.Instance.SetVal(RegNameList[0], double.Parse(ar_line[4]));
                    }
                    if (autoMode && Succ_R>10)
                        autoGet = true;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 生成写入寄存器的通讯帧
        /// </summary>
        /// <param name="NeedRecvLen"></param>
        /// <returns></returns>
        public override byte[] GenerateWriteFrame(out int NeedRecvLen)
        {
            startTicks = Environment.TickCount;
            NeedRecvLen = 0;
            return null;
        }

        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override bool ProcessWriteFrame(byte[] buffer)
        {
            Lapse = Environment.TickCount - startTicks;
            return true;
        }

        /// <summary>
        /// 改变变量的值
        /// </summary>
        /// <param name="Index"></param>
        /// <param name="Value"></param>
        public override void PushRegValue(int Index, double Value)
        {
            Index -= 1;  //寄存器存储顺序从0开始，先是只读存储器，后面是读写存储器
            var DataFactory = RegFactory.Instance;

            if (Index == 0 && Value == 1)
            {
                autoMode = true;
                autoGet = false;
                Succ_R = 0;
                DataFactory.SetVal(RegNameList[1 + Index], Value);
                DataFactory.SetVal(RegNameList[2 + Index], 0);
            } else if (Index == 1 && Value == 1) {
                autoMode = false;
                DataFactory.SetVal(RegNameList[0 + Index], 0);
                DataFactory.SetVal(RegNameList[1 + Index], Value);
            }
        }
    }
}
